#include "cmdline_parser.hpp"
#include "log.hpp"

namespace sdl_engine {

CmdLinePaser::CmdLinePaser(int argc, char** argv) {
    for (int i = 1; i < argc; i++)
        parse(argv[i]);
}

std::string_view CmdLinePaser::Get(const std::string& key) const {
    auto it = params_.find(key);
    if (it != params_.end())
        return it->second;
    return std::string_view();
}

bool CmdLinePaser::Has(const std::string& key) const {
    return params_.find(key) != params_.end();
}

void CmdLinePaser::parse(char* block) {
    if (!block)
        return;

    int idx= 0 ;
    int minusCharNum = 0;
    while (block[idx] && block[idx] == '-') {
        idx ++;
        minusCharNum ++;
    }
    if (minusCharNum > 2 || minusCharNum <= 0) {
        Logw(Fmt("Invalid format in %s", block));
        return ;
    }
    if (minusCharNum == 1) {
        std::string key;
        while (block[idx]) {
            key.push_back(block[idx ++]);
        }
        put(key, "");
    }
    if (minusCharNum == 2) {
        std::string key;
        while (block[idx] && block[idx] != '=') {
            key.push_back(block[idx]);
            idx ++;
        }
        if (block[idx] != '=') {
            Logw(Fmt("Invalid format in %s", block));
            return ;
        }
        params_[key] = getRemainStr(block + (++ idx));
    }
}

std::string CmdLinePaser::getRemainStr(const char* str) {
    if (!str)
        return "";
    std::string result;
    while (*str) {
        result.push_back(*str);
        str ++;
    }
    return result;
}

void CmdLinePaser::put(const std::string& key, const std::string& value) {
    if (params_.find(key) != params_.end()) {
        Logw(Fmt("parameter %s already exists, don't record this", key.c_str()));
    } else {
        params_[key] = value;
    }
}

}
